package auth

import (
	"go-proxy/common"
	"go-proxy/config"
	"net/http"
	"sync"
)

var (
	authMap  = make(map[string]*config.Auth)
	authLock sync.RWMutex

	authHandlerMap = map[string]HandlerAuth{
		common.HttpBasicAuth: NewHttpBasicAuth(),
		common.JwtAuth:       NewJwtAuth(),
	}
)

type HandlerAuth interface {
	checkAuth(w http.ResponseWriter, r *http.Request, auth *config.Auth) bool
}

func InitAuthConfig() {
	auths := config.ProxyConfigData.Auths
	if len(auths) <= 0 {
		return
	}

	for _, auth := range auths {
		SetAuthConfig(&auth)
	}
}

func SetAuthConfig(auth *config.Auth) {
	authLock.Lock()
	defer authLock.Unlock()
	authMap[auth.Name] = auth
}

func GetAuthConfig(authName string) *config.Auth {
	authLock.RLock()
	defer authLock.RUnlock()
	return authMap[authName]
}

func HandleAuth(w http.ResponseWriter, r *http.Request, authName string) bool {
	if len(authName) <= 0 {
		return true
	}

	auth := GetAuthConfig(authName)
	if auth == nil || !auth.Enable {
		return true
	}

	handler, ok := authHandlerMap[auth.AuthType]
	if !ok {
		return true
	}

	return handler.checkAuth(w, r, auth)
}
